const { parse: vueParse, transform: vueTransform } = require('@vue/compiler-dom');
const MagicString = require('magic-string');
const EXCLUDE_TAG = ['template', 'script', 'style']
const KEY_DATA = 'data-v-inspector';
async function compileSFCTemplate({ code, id, type, 透传dataVInspector }) {
    try {
        const s = new MagicString(code);
        // const relativePath = path.relative(process.cwd(), id);
        const relativePath = id

        const result = await new Promise((resolve) => {
            switch (type) {
                case 'template': {
                    const ast = vueParse(code, { comments: true });
                    vueTransform(ast, {
                        nodeTransforms: [
                            (node) => {
                                if (node.type === 1) {
                                    const insertPosition = node.props.length ? Math.max(...node.props.map(i => i.loc.end.offset)) : node.loc.start.offset + node.tag.length + 1
                                    const { line, column } = node.loc.start

                                    const content = ` ${KEY_DATA}="${relativePath}:${line}:${column}"`

                                    s.prependLeft(
                                        insertPosition,
                                        content,
                                    )
                                }
                            },
                        ],
                    });
                    break;
                }
                default:
                    break;
            }
            resolve(s.toString());
        });
        return result;
    } catch (err) {
        console.log(err)
    }


}

function viteDevInspector() {
    return {
        name: 'vite-dev-inspector',
        enforce: 'pre',
        apply(_, { command }) {
            // apply only on serve and not for test
            return command === 'serve' && process.env.NODE_ENV !== 'test';
        },
        transform(code, id) {
            if (id.endsWith('.vue')) {
                return compileSFCTemplate({ code, id, type: 'template' });
            }
        },
    };
}

module.exports = viteDevInspector;
